# -*- coding: UTF-8 -*-
import logging
import os
from logging.handlers import RotatingFileHandler

from flask import Flask

from extention import jwt
from web.config import Config


def init_log(app):
    formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s File [%(filename)s] '
        'in [%(funcName)s] [line:%(lineno)d] %(message)s')
    error_log = os.path.join(app.root_path, app.config["ERROR_LOG"])
    if not os.path.exists(os.path.dirname(error_log)):
        os.makedirs(os.path.dirname(error_log))
    error_file_handler = RotatingFileHandler(
        error_log,
        maxBytes=1024 * 1024 * 1024,
        backupCount=10
    )
    error_file_handler.setLevel(logging.ERROR)
    error_file_handler.setFormatter(formatter)
    app.logger.addHandler(error_file_handler)
    info_log = os.path.join(app.root_path, app.config["INFO_LOG"])
    info_file_handler = RotatingFileHandler(
        info_log,
        maxBytes=1024 * 1024 * 1024,
        backupCount=10
    )
    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(formatter)
    app.logger.addHandler(info_file_handler)
    app.logger.setLevel(logging.DEBUG)


def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    jwt.init_app(app)
    from web.http_api import web
    from web.receive_api import m_web
    app.register_blueprint(web)
    app.register_blueprint(m_web)
    init_log(app)
    return app
